<?php
if (!isset($___MEDIA__UPLOAD__TPL__INCLUDE)) {
    $___MEDIA__UPLOAD__TPL__INCLUDE = true;
    ?>
    <!-- 确保只加载一次 -->
    <style>
        .mediaChooseUploadDialog {
            padding: 10px;
        }

        .mediaItem {
            width: 100px;
            height: 100px;
            float: left;
            margin: 0 20px 15px 0;
            border: solid 2px #fff;
        }

        .mediaItem.hover,
        .mediaItem.selected {
            border: solid 2px #1E9FFF;
        }

        .mediaItem .remove {
            position: relative;
            bottom: 110px;
            float: right;
            color: #333;
            cursor: pointer;
            left: 15px;
        }

        .mediaItem .remove i {
            font-size: 22px;
        }

        .mediaItem .checked {
            display: none;
        }

        .mediaItem.selected .checked {
            display: initial;
            position: relative;
            bottom: 120px;
            float: right;
            color: #1E9FFF;
            font-weight: 900;
        }

        .mediaItem .image {
            width: 100px;
            height: 100px;
            text-align: center;
            display: table-cell;
            vertical-align: middle;
            color: #fff;
            border: solid 1px #e0e0e0;
        }

        .mediaItem .image img {
            width: 100%;
            height: 100%;
        }

        .mediaItem .image i {
            font-size: 35px;
        }

        .mediaItem .text {
            text-align: center;
            bottom: 20px;
            line-height: 20px;
            height: 20px;
            position: relative;
            background: rgba(128, 128, 128, 0.8);
            color: #fff;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            padding: 0 3px;
        }

        .mediaList {
            overflow-y: auto;
        }

        .mediaListPager {
            text-align: center;
        }

        .mediaResultList .mediaItem {
            border: none;
            padding-top: 10px;
        }
    </style>

    <!-- 媒体上传对话框 -->
    <div class="mediaChooseUploadDialog" id="mediaChooseUploadDialog" style="display: none;">
        <div class="layui-form" action="#" lay-filter="mediaUploadSearch">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <input type="text" class="layui-input" lay-filter="date" placeholder="请选择日期范围">
                    </div>
                    <div class="layui-input-inline">
                        <select lay-filter="type">
                            <option value="file">所有文件类型</option>
                            <option value="image">图片</option>
                            <option value="voice">语音</option>
                        </select>
                    </div>
                    <div class="layui-input-inline">
                        <input type="text" placeholder="文件名称" autocomplete="off" class="layui-input"
                               lay-filter="keyword"/>
                    </div>
                    <div class="layui-input-inline layui-input-inline-auto">
                        <button class="layui-btn" type="button" title="搜索" lay-filter="search">
                            <i class="layui-icon layui-icon-search"></i>
                        </button>
                    </div>
                    <div class="layui-input-inline layui-input-inline-auto">
                        <button class="layui-btn" type="button" title="上传" lay-filter="upload">
                            <i class="layui-icon layui-icon-upload-drag"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <div id="availableMediaList" class="layui-clear mediaList"></div>
        <div id="availableMediaListPager" class="mediaListPager"></div>
    </div>

    <script>
        $(document).ready(function () {
            var laydate;
            var upload;
            var form;
            var laypage;
            var uploader;
            var $dlg;
            var $availableMediaList;

            pageInit();

            /**
             * 页面初始化
             */
            function pageInit() {
                // 将对话框对应的div放置到最外层，防止被form-item包裹之后无法弹出。
                var html = $("#mediaChooseUploadDialog").prop("outerHTML");
                $("#mediaChooseUploadDialog").remove();
                $("body").append(html);

                //元素
                $dlg = $("#mediaChooseUploadDialog");
                $availableMediaList = $("#mediaChooseUploadDialog #availableMediaList");

                // layui初始化
                layui.use(['laydate', 'upload', 'form', 'laypage'], function () {
                    laydate = layui.laydate;
                    upload = layui.upload;
                    form = layui.form;
                    laypage = layui.laypage;

                    // 上传组件初始化
                    var uploadOptions = {};
                    uploadOptions.elem = "#mediaChooseUploadDialog button[lay-filter='upload']";
                    uploadOptions.before = function () {
                        g.loading(uploadOptions.elem);
                    };
                    uploadOptions.error = function () {
                        g.loading(uploadOptions.elem, false);
                    };
                    uploader = upload.render(uploadOptions);
                });

                // 绑定选择按钮
                $("body").delegate(".mediaChooseUploadBtn", "click", function () {
                    var btnThis = this;
                    var type = $(btnThis).attr("data-type");
                    var multi = $(btnThis).attr("data-multi")
                    var fieldNameFix = $(btnThis).attr('data-field');
                    var uploadEnable = $(btnThis).attr("data-upload");
                    var value = $(btnThis).attr("data-value");
                    var opt = {};
                    opt.type = type ? type : 'file';
                    opt.multi = multi;
                    opt.fieldNameFix = fieldNameFix;
                    opt.uploadEnable = uploadEnable;
                    opt.mediaInfos = value ? eval("(" + value + ")") : [];
                    opt.callback = function (mediaInfos) {
                        g.upload.set(btnThis.id, mediaInfos);
                    };
                    //显示对话框
                    showMediaChooseUploadDialog(opt);
                });

                // 初始化
                $(".mediaChooseUploadBtn").each(function () {
                    var initValue = $(this).attr("data-value");
                    if (!initValue) {
                        return;
                    }
                    var mediaInfos = eval("(" + initValue + ")");
                    g.upload.set(this.id, mediaInfos);
                });

                // 搜索按钮事件绑定
                $dlg.find('button[lay-filter="search"]').click(function () {
                    searchRenderavailableMediaList();
                });

                // 列表事件绑定
                $availableMediaList.delegate(".mediaItem", "mouseenter", function () {
                    $(this).addClass("hover");
                });
                $availableMediaList.delegate(".mediaItem", "mouseleave", function () {
                    $(this).removeClass("hover");
                });
                $availableMediaList.delegate(".mediaItem", "click", function () {
                    var mediaId = $(this).attr("data-media_id");
                    var filename = $(this).attr("title");
                    var url = $(this).attr("data-url");
                    var type = $(this).attr("data-type");
                    var mediaInfo = {
                        'media_id': mediaId,
                        'filename': filename,
                        'url': url,
                        'type': type
                    };
                    if ($(this).hasClass("selected")) {
                        $(this).removeClass("selected");
                        $(this).removeClass("hover");
                        markMediaInfoUnselectedInAvaliableList(mediaInfo);
                    } else {
                        var multi = $dlg.attr("data-multi");
                        if (multi == true || multi == 'true') {
                            // 支持多选
                            $(this).addClass("selected");
                            markMediaInfoSelectedInAvaliableList(mediaInfo);
                        } else {
                            var currentClickThis = this;
                            // 不支持多选
                            $availableMediaList.find(".mediaItem").each(function () {
                                var mediaId = $(this).attr("data-media_id");
                                var filename = $(this).attr("title");
                                var url = $(this).attr("data-url");
                                var type = $(this).attr("data-type");
                                var mediaInfo = {
                                    'media_id': mediaId,
                                    'filename': filename,
                                    'url': url,
                                    'type': type
                                };
                                if (this != currentClickThis) {
                                    $(this).removeClass("selected");
                                    markMediaInfoUnselectedInAvaliableList(mediaInfo);
                                } else {
                                    $(this).addClass("selected");
                                    markMediaInfoSelectedInAvaliableList(mediaInfo);
                                }
                            });
                        }
                    }
                });
            }

            /**
             * 显示媒体管理对话框
             *
             * @param opt
             */
            function showMediaChooseUploadDialog(opt) {
                if (!opt) {
                    opt = {};
                }
                var option = {
                    //文件类型，可选：image、voice、file
                    type: 'file',
                    enableUpload: true,
                    title: '媒体管理',
                    multi: false,
                    fieldNameFix: '',
                    uploadEnable: true,
                    callback: function () {
                    },
                    mediaInfos: []
                };
                $.extend(option, opt);
                var height = (window.frameElement ? $(window.frameElement).height() : $(window).height()) - 50;
                if (height > 800) {
                    height = 800;
                }
                var width = (window.frameElement ? $(window.frameElement).width() : $(window).width()) - 50;
                if (width > 1500) {
                    width = 1500;
                }

                // 上传组件配置
                uploader.config.field = option.fieldNameFix + "file";
                uploader.config.url = '/core/enterprise.media/upload?mid=<?php echo $mid ?>&field=' + uploader.config.field;
                switch (option.type) {
                    case "image":
                    case "images":
                        uploader.config.accept = "images";
                        uploader.config.acceptMime = 'image/*';
                        break;
                    case "voice":
                    case "audio":
                        uploader.config.accept = "audio";
                        uploader.config.acceptMime = 'audio/*';
                        break;
                    case "file":
                    default:
                        uploader.config.accept = "file";
                        break;
                }
                $dlg.find("button[lay-filter='upload']").parent().find(".layui-upload-file").attr("accept", uploader.config.acceptMime);
                uploader.config.done = function (res) {
                    g.loading(uploader.config.elem, false);
                    if (res.code == 0) {
                        layer.alert(res.msg);
                    } else {
                        addMediaToAvaliableList(res.data, true);
                    }
                };
                if (option.uploadEnable == 'false' || option.uploadEnable == false) {
                    $dlg.find("button[lay-filter='upload']").hide();
                } else {
                    $dlg.find("button[lay-filter='upload']").show();
                }

                // 是否支持多选
                $dlg.attr("data-multi", option.multi);

                // 日期组件初始化
                var dateOptions = {};
                dateOptions.elem = '#mediaChooseUploadDialog input[lay-filter="date"]';
                dateOptions.type = 'date';
                dateOptions.range = '~';
                dateOptions.format = 'yyyy-M-d';
                if (option.start && option.end) {
                    // 初始值
                    dateOptions.value = option.start + " " + dateOptions.range + " " + option.end;
                }
                laydate.render(dateOptions);

                // 初始化类型选择
                if (option.type == 'file') {
                    $dlg.find("select[lay-filter='type'] option").attr("disabled", false);
                } else {
                    $dlg.find("select[lay-filter='type'] option").attr("disabled", true);
                    $dlg.find("select[lay-filter='type'] option[value='" + option.type + "']").attr("disabled", false);
                    $dlg.find("select[lay-filter='type']").val(option.type);
                }
                form.render('select', 'mediaUploadSearch');

                // 列表初始化
                $availableMediaList.data("mediaInfos", option.mediaInfos);
                $availableMediaList.css('height', (height - 210) + "px")
                searchRenderavailableMediaList();

                // 显示对话框
                layer.open({
                    type: 1
                    , title: option.title
                    , closeBtn: false
                    , area: [width + 'px', height + 'px']
                    , shade: 0.8
                    , shadeClose: true
                    , id: 'LAY_mediaUploadDialog' //设定一个id，防止重复弹出
                    , btn: ['确定', '取消']
                    , btnAlign: 'c'
                    , moveType: 1 //拖拽模式，0或者1
                    , content: $dlg
                    , success: function (layero) {
                    }
                    , yes: function (index, layero) {
                        //确定按钮的回调
                        var mediaInfos = $availableMediaList.data("mediaInfos");
                        option.callback(mediaInfos);
                        layer.close(index);
                        return true;
                    }
                });
            }

            /**
             * 将媒体添加到列表
             */
            function addMediaToAvaliableList(mediaInfo, prepend) {
                var selected = isMediaInfoSelectedInAvaliableList(mediaInfo) ? "selected" : "";
                var html = "<div class='mediaItem " + selected + "' " +
                    "data-media_id='" + mediaInfo.media_id + "' " +
                    "data-type='" + mediaInfo.type + "' " +
                    "data-url='" + mediaInfo.url + "' " +
                    "title='" + mediaInfo.filename + "'>";
                html += "<div class='image'>";
                if (mediaInfo.type == 'image') {
                    html += "<img src='" + mediaInfo.url + "'/>";
                } else if (mediaInfo.type == 'voice') {
                    html += "<i class='layui-icon layui-icon-voice'></i>";
                } else {
                    html += "<i class='layui-icon layui-icon-link'></i>";
                }
                html += "</div>";
                html += "<div class='text'>" + mediaInfo.filename + "</div>";
                html += "<div class='checked'><i class='layui-icon layui-icon-ok-circle'></i></div>";
                html += "</div>";
                if (prepend) {
                    $availableMediaList.prepend(html);
                } else {
                    $availableMediaList.append(html);
                }
            }

            /**
             * 检查某个媒体是否被选中
             */
            function isMediaInfoSelectedInAvaliableList(mediaInfo) {
                var selectedMediaInfos = $availableMediaList.data("mediaInfos");
                if (!selectedMediaInfos) {
                    return false;
                }
                for (var i = 0; i < selectedMediaInfos.length; i++) {
                    if (selectedMediaInfos[i].media_id == mediaInfo.media_id) {
                        return true;
                    }
                }
                return false;
            }

            /**
             * 记录媒体被选中
             */
            function markMediaInfoSelectedInAvaliableList(mediaInfo) {
                var selectedMediaInfos = $availableMediaList.data("mediaInfos");
                if (!selectedMediaInfos) {
                    selectedMediaInfos = [];
                }
                var newSelectedMediaInfos = [];
                for (var i = 0; i < selectedMediaInfos.length; i++) {
                    if (selectedMediaInfos[i].media_id == mediaInfo.media_id) {
                        return;
                    }
                    newSelectedMediaInfos.push(selectedMediaInfos[i]);
                }
                newSelectedMediaInfos.push(mediaInfo);
                $availableMediaList.data("mediaInfos", newSelectedMediaInfos);
            }

            /**
             * 记录媒体未被选中
             */
            function markMediaInfoUnselectedInAvaliableList(mediaInfo) {
                var selectedMediaInfos = $availableMediaList.data("mediaInfos");
                if (!selectedMediaInfos) {
                    return;
                }
                var newSelectedMediaInfos = [];
                for (var i = 0; i < selectedMediaInfos.length; i++) {
                    if (selectedMediaInfos[i].media_id == mediaInfo.media_id) {
                        continue;
                    }
                    newSelectedMediaInfos.push(selectedMediaInfos[i]);
                }
                $availableMediaList.data("mediaInfos", newSelectedMediaInfos);
            }

            /**
             * 渲染列表
             */
            function searchRenderavailableMediaList(pageNum) {
                var dateRange = $dlg.find('input[lay-filter="date"]').val();
                var param = {};
                param.startDate = "";
                param.endDate = "";
                if (dateRange) {
                    var items = dateRange.split(" ~ ");
                    param.startDate = items[0];
                    param.endDate = items[1];
                }
                param.type = $dlg.find('select[lay-filter="type"]').val();
                param.keyword = $dlg.find('input[lay-filter="keyword"]').val();
                param.pageNum = pageNum ? pageNum : 1;
                param.mid = '<?php echo $mid; ?>';

                g.loading($availableMediaList);
                $.post("/core/enterprise.media/query", param, function (ret) {
                    g.loading($availableMediaList, false);
                    if (ret.code == 0) {
                        layer.alert(ret.msg);
                    } else {
                        $availableMediaList.html("");
                        for (var i = 0; i < ret.data.rows.length; i++) {
                            var row = ret.data.rows[i];
                            addMediaToAvaliableList(row);
                        }
                        laypage.render({
                            elem: 'availableMediaListPager'
                            , count: ret.data.count
                            , limit: ret.data.pageSize
                            , curr: ret.data.pageNum
                            , jump: function (obj, first) {
                                console.log(obj);
                                if (!first) {
                                    searchRenderavailableMediaList(obj.curr);
                                }
                            }
                        });
                    }
                }, "json");
            }

            /**
             * 将选择的结果渲染在按钮上
             */
            function renderMediaResultToBtn(mediaInfos, $btn) {
                if ($btn.find("span").length == 0) {
                    $btn.append("<span></span>");
                }
                $btn.find("span").html(mediaInfos.length > 0 ? ("(" + mediaInfos.length + ")") : "");
            }

            /**
             * 将选择的结果放置到容器中
             *
             * @param mediaInfos
             * @param elemSelector
             * @param fieldNameFix
             * @param id
             */
            function renderMediaResultToElem(mediaInfos, elemSelector, fieldNameFix, id) {
                var $elem = $(elemSelector);
                $elem.html("");
                var html = "<div class='layui-clear mediaList mediaResultList'>";
                for (var i = 0; i < mediaInfos.length; i++) {
                    var mediaInfo = mediaInfos[i];
                    html += "<div class='mediaItem' data-media_id='" + mediaInfo.media_id + "' data-url='" + mediaInfo.url + "' title='" + mediaInfo.filename + "'>";
                    html += "<input type='hidden' name='" + fieldNameFix + "MediaId[]' value='" + mediaInfo.media_id + "'/>";
                    html += "<input type='hidden' name='" + fieldNameFix + "MediaUrl[]' value='" + mediaInfo.url + "'/>";
                    html += "<input type='hidden' name='" + fieldNameFix + "MediaType[]' value='" + mediaInfo.type + "'/>";
                    html += "<div class='image'>";
                    if (mediaInfo.type == 'image') {
                        html += "<img src='" + mediaInfo.url + "'/>";
                    } else if (mediaInfo.type == 'audio') {
                        html += "<i class='layui-icon layui-icon-voice'></i>";
                    } else {
                        html += "<i class='layui-icon layui-icon-link'></i>";
                    }
                    html += "</div>";
                    html += "<div class='text' style='" + mediaInfo.filename ? "" : "display:none" + "'>" + mediaInfo.filename + "</div>";
                    html += "<div class='remove' title='移除' onclick='g.upload.remove(\"" + id + "\", \"" + mediaInfo.media_id + "\")'>" +
                        "<i class='layui-icon layui-icon-close-fill'></i>" +
                        "</div>";
                    html += "</div>";
                }
                html += "</div>";
                $elem.html(html);
            }

            /**
             * 全局对象
             */
            g.upload = {
                getBtn: function (id) {
                    if (id.indexOf("mediaChooseUploadBtn_") !== 0) {
                        id = "mediaChooseUploadBtn_" + id;
                    }
                    return $("#" + id);
                },
                get: function (id) {
                    var $btn = g.upload.getBtn(id);
                    var mediaInfos = $btn.attr("data-value");
                    return eval("(" + mediaInfos + ")");
                },
                set: function (id, mediaInfos) {
                    var $btn = g.upload.getBtn(id);
                    var fieldNameFix = $btn.attr('data-field');
                    var resultElem = $btn.attr('data-result');
                    var callback = $btn.attr('data-callback');
                    if (callback) {
                        mediaInfos = eval("(" + callback + ")");
                    }
                    $btn.attr("data-value", JSON.stringify(mediaInfos));
                    if (resultElem && resultElem != 'false') {
                        //将选择结果渲染到结果面板
                        renderMediaResultToElem(mediaInfos, resultElem, fieldNameFix, id);
                    } else {
                        renderMediaResultToBtn(mediaInfos, $btn);
                    }
                },
                remove: function (id, mediaId) {
                    var $btn = g.upload.getBtn(id);
                    var mediaInfos = $btn.attr("data-value");
                    mediaInfos = eval("(" + mediaInfos + ")");
                    var newMediaInfos = [];
                    for (var i = 0; i < mediaInfos.length; i++) {
                        if (mediaInfos[i].media_id == mediaId) {
                            continue;
                        }
                        newMediaInfos.push(mediaInfos[i]);
                    }
                    g.upload.set(id, newMediaInfos);
                }
            };
        });
    </script>

    <?php
}
?>